package com.ykdl.member.kid.regandlogin;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;

import net.wxxr.dataparse.model.DataParseError;
import net.wxxr.dataparse.model.DataState;
import net.wxxr.http.interfaces.ITag;
import net.wxxr.http.request.HttpBaseRequest;
import oauth.signpost.http.HttpParameters;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Paint;
import android.net.ParseException;
import android.os.Bundle;
import android.text.TextUtils;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.ykdl.member.base.QLog;
import com.ykdl.member.constant.KidAction;
import com.ykdl.member.constant.KidConfig;
import com.ykdl.member.kid.R;
import com.ykdl.member.kid.beans.ResetPasswordBean;
import com.ykdl.member.kid.circle.RecommendCircle;
import com.ykdl.member.kid.gears.BaseScreen;
import com.ykdl.member.kid.marketcard.CardPersonalInformationActivity;
import com.ykdl.member.kid.messagebox.MyMessageAcivity1;
import com.ykdl.member.kid.messagebox.OfficialMessageActivity1;
import com.ykdl.member.kid.set.PredateSetActivity;
import com.ykdl.member.kid.util.LocationUtils;
import com.ykdl.member.kid.util.ResoureUtil;
import com.ykdl.member.kid.util.LocationUtils.onLocationChangeListener;
import com.ykdl.member.views.MyWheelView;
import com.ykdl.member.views.MyWheelView.OnWheelViewDataChanger;
import com.ykdl.net.manager.TaskManager;
import com.ykdl.net.manager.Wxxr;

/**
 * 完善资料
 * 
 * @author wangcaisheng
 * 
 */
public class PerfectUserInfoActivity1 extends BaseScreen implements
		OnTouchListener {
	private EditText baby_birthday, user_place;
	private MyWheelView wheel_time;
	private MyWheelView location;
	private long babybirthday;
	final String[] genderaray = new String[] { "女宝宝", "男宝宝" };
	private int gender_index = -1;
	private ImageView mImgSex;
	private TextView gender, calculator;
	private boolean isSetTime = false;
	private Button back_bt;
	private boolean isShow = false;
	private String place_string = "";
	private String come_from = "";
	private LinearLayout head;
	private ImageView boy_icon, girl_icon;
	private boolean boy_selected = false;
	private boolean girl_selected = false;
	private String[] theTime;
	private boolean first = false;
//	public LocationClient mLocationClient = null;
//	public BDLocationListener myListener = new MyLocationListener();
	private String[] ZXS = { "北京市", "上海市", "天津市", "重庆市" };
	private String placeString = "";

	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.perfectuserinfoactivity_xml1);
		ResoureUtil.activityList.add(this);
		come_from = this.getIntent().getStringExtra("COMEFROM");
		// 是否开启GPRS定位对话框
				AlertDialog.Builder dialog = new AlertDialog.Builder(this);
				dialog.setMessage("是否开启GPRS定位")
						.setPositiveButton("是",
								new DialogInterface.OnClickListener() {

									@Override
									public void onClick(DialogInterface dialog,
											int which) {
										// TODO Auto-generated method stub
										first = true;
										initLocation();
									}
								})
						.setNegativeButton("否",
								new DialogInterface.OnClickListener() {

									@Override
									public void onClick(DialogInterface dialog,
											int which) {
										// TODO Auto-generated method stub
										dialog.dismiss();
									}
								});
				dialog.create().show();
		init();

	}
	private LocationUtils mLocationUtils;
	private void initLocation(){
		mLocationUtils = LocationUtils.getInstance(getApplication());
		mLocationUtils.setLocationListener(new onLocationChangeListener() {
			
			@Override
			public void locationChange(BDLocation location) {
				if(first){
					if(isHave(ZXS,location.getProvince())){
						user_place.setText(location.getProvince()+","+location.getDistrict());
						placeString=location.getProvince()+","+location.getDistrict();
					}else{
						user_place.setText(location.getProvince()+","+location.getCity());
						placeString=location.getProvince()+","+location.getCity();
					}
					Log.d(TAG, "city " +location.getCity()+"getProvince():"+location.getProvince()+"--getDistrict:"+location.getDistrict());
					first=false;
					mLocationUtils.stop();
				}
			}
		});
		mLocationUtils.start();
	}
	/*
	 * 此方法有两个参数，第一个是要查找的字符串数组，第二个是要查找的字符或字符串
	 */
	public boolean isHave(String[] strs, String s) {
		for (int i = 0; i < strs.length; i++) {
			if (strs[i].indexOf(s) != -1) {// 循环查找字符串数组中的每个字符串中是否包含所有查找的内容
				return true;// 查找到了就返回真，不在继续查询
			}
		}
		return false;// 没找到返回false
	}
	
	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		mLocationUtils.stop();
	}
	
//	public void startGPRS() {
//		// GPRS进行定位
//		mLocationClient = new LocationClient(getApplicationContext()); // 声明LocationClient类
//		mLocationClient.setAccessKey("NY7EkMAtsFmPLzMAW1mskdHG");
//		mLocationClient.registerLocationListener(myListener); // 注册监听函数
//		setLocationOption();
//		// showProgress("正在加载中,请稍等...");
//		mLocationClient.start();// 开始定位
//	}
//	
//	/**
//	 * GPRS设置相关参数
//	 */
//	private void setLocationOption() {
//		LocationClientOption option = new LocationClientOption();
//		option.setOpenGps(true);
//		option.setIsNeedAddress(true); // 返回的定位结果包含地址信息
//		option.setAddrType("all"); // 返回的定位结果包含地址信息
//		option.setCoorType("bd09ll"); // 返回的定位结果是百度经纬度,默认值gcj02
//		option.setScanSpan(5000); // 设置发起定位请求的间隔时间为5000ms
//		option.disableCache(true); // 禁止启用缓存定位
//		option.setPoiNumber(5); // 最多返回POI个数
//		option.setPoiDistance(1000); // poi查询距离
//		option.setPoiExtraInfo(true); // 是否需要POI的电话和地址等详细信息
//		mLocationClient.setLocOption(option);
//	}
//	
//	public class MyLocationListener implements BDLocationListener {
//		@Override
//		public void onReceiveLocation(BDLocation location) {
//			if (location == null)
//				return;
//			StringBuffer sb = new StringBuffer(256);
//			sb.append("time : ");
//			sb.append(location.getTime());
//			sb.append("\nerror code : ");
//			sb.append(location.getLocType());
//			sb.append("\nlatitude : ");
//			sb.append(location.getLatitude());
//			sb.append("\nlontitude : ");
//			sb.append(location.getLongitude());
//			sb.append("\nradius : ");
//			sb.append(location.getRadius());
//			if (location.getLocType() == BDLocation.TypeGpsLocation) {
//				sb.append("\nspeed : ");
//				sb.append(location.getSpeed());
//				sb.append("\nsatellite : ");
//				sb.append(location.getSatelliteNumber());
//			} else if (location.getLocType() == BDLocation.TypeNetWorkLocation) {
//				sb.append("\naddr : ");
//				sb.append(location.getAddrStr());    //地址
//			}
//			
//			Log.d(TAG, "onReceiveLocation " + sb.toString());
//			if(first){
//				if(isHave(ZXS,location.getProvince())){
//					user_place.setText(location.getProvince()+","+location.getDistrict());
//					placeString=location.getProvince()+","+location.getDistrict();
//				}else{
//					user_place.setText(location.getProvince()+","+location.getCity());
//					placeString=location.getProvince()+","+location.getCity();
//				}
//				Log.d(TAG, "city " +location.getCity()+"getProvince():"+location.getProvince()+"--getDistrict:"+location.getDistrict());
//				first=false;
//			}
//		}
//
//		
//
//		public void onReceivePoi(BDLocation poiLocation) {
//			// 将在下个版本中去除poi功能
//			if (poiLocation == null) {
//				return;
//			}
//			StringBuffer sb = new StringBuffer(256);
//			sb.append("Poi time : ");
//			sb.append(poiLocation.getTime());
//			sb.append("\nerror code : ");
//			sb.append(poiLocation.getLocType());
//			sb.append("\nlatitude : ");
//			sb.append(poiLocation.getLatitude());
//			sb.append("\nlontitude : ");
//			sb.append(poiLocation.getLongitude());
//			sb.append("\nradius : ");
//			sb.append(poiLocation.getRadius());
//			if (poiLocation.getLocType() == BDLocation.TypeNetWorkLocation) {
//				sb.append("\naddr : ");
//				sb.append(poiLocation.getAddrStr());
//			}
//			if (poiLocation.hasPoi()) {
//				sb.append("\nPoi:");
//				sb.append(poiLocation.getPoi());
//			} else {
//				sb.append("noPoi information");
//			}
//			// mTextPoi.setText(sb.toString());
//			Log.d(TAG, "onReceiveLocation " + sb.toString());
//		}
//	}

	private void SwitchXml() {
		// TODO Auto-generated method stub
		if (come_from.equals("yunqi")) {
			baby_birthday.setHint("预产期   预产期是哪一天呢");
			calculator = (TextView) findViewById(R.id.calculator);
			calculator.setVisibility(View.VISIBLE);
			calculator.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG);// 下划线
			calculator.setTextColor(Color.RED);
			head.setVisibility(View.GONE);
			calculator.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					Intent intent = new Intent(mContext,
							PredateSetActivity.class);
					startActivityForResult(intent, 100);
				}
			});
		} else if (come_from.equals("baby")) {

			baby_birthday.setHint("宝宝生日");
			boy_icon.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					if (boy_selected) {
						boy_icon.setBackgroundResource(R.drawable.boy_not_laugh);
						girl_icon.setBackgroundResource(R.drawable.girl_laugh);
						girl_selected = true;
						boy_selected = false;
						
					} else {
						
						boy_icon.setBackgroundResource(R.drawable.boy_laugh);
						boy_selected = true;
						girl_icon.setBackgroundResource(R.drawable.girl_not_laugh);
				        girl_selected = false;
					}
				}
			});
			girl_icon.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					if (girl_selected) {
						girl_icon.setBackgroundResource(R.drawable.girl_not_laugh);
						girl_selected = false;
						boy_icon.setBackgroundResource(R.drawable.boy_laugh);
						boy_selected = true;
					} else {
						girl_icon.setBackgroundResource(R.drawable.girl_laugh);
						girl_selected = true;
						boy_icon.setBackgroundResource(R.drawable.boy_not_laugh);
						boy_selected = false;
					}
				}
			});
		} else {
			baby_birthday.setHint("您的生日");
			head.setVisibility(View.GONE);
		}
	}

	public void init() {
		isSetTime = false;
		baby_birthday = (EditText) findViewById(R.id.baby_birthday);
		user_place = (EditText) findViewById(R.id.user_place);
		baby_birthday.setOnTouchListener(this);
		user_place.setOnTouchListener(this);
		gender = (TextView) findViewById(R.id.iask_gender);
		back_bt = (Button) findViewById(R.id.back_bt);
		head = (LinearLayout) findViewById(R.id.head);
		boy_icon = (ImageView) findViewById(R.id.boy_icon);
		girl_icon = (ImageView) findViewById(R.id.girl_icon);
		SwitchXml();
		findViewById(R.id.back_bt).setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				finish();
			}
		});
		findViewById(R.id.turn_ok).setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				profileUserInfo();
			}
		});
		wheel_time = (MyWheelView) findViewById(R.id.account_wheel_time);
		if(come_from.equals("yunqi")){
			wheel_time.setTimeAfterNow(true);
		}
		wheel_time.setWheelView(MyWheelView.CALENDAR);
		wheel_time.findViewById(R.id.my_wheelview_cancel).setOnClickListener(
				new OnClickListener() {

					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						wheel_time.setMyGone();
					}

				});
		wheel_time.setOnWheelViewDataChanger(new OnWheelViewDataChanger() {

			@Override
			public void updataByChanger(String data) {
				// TODO Auto-generated method stub
				((InputMethodManager) getSystemService(INPUT_METHOD_SERVICE))
						.hideSoftInputFromWindow(PerfectUserInfoActivity1.this
								.getCurrentFocus().getWindowToken(),
								InputMethodManager.HIDE_NOT_ALWAYS);
				String[] time = data.split(",");
				theTime = time;
				baby_birthday.setTextColor(Color.parseColor("#3e3e3e"));
				baby_birthday.setText(time[0] + "年" + time[1] + "月" + time[2]+ "日");
				Date now = new Date();
				now.setYear(Integer.parseInt(time[0]) - 1900);
				now.setMonth(Integer.parseInt(time[1]) - 1);
				now.setDate(Integer.parseInt(time[2]));
				babybirthday = now.getTime() / 1000;
				isSetTime = true;
			}

		});
		location = (MyWheelView) findViewById(R.id.select_location_layout);
		location.setWheelView(MyWheelView.CHINA);
		location.setOnWheelViewDataChanger(new OnWheelViewDataChanger() {
			@Override
			public void updataByChanger(String data) {
				QLog.debug("data", data);
				String[] datas = data.split("&#&");
				String[] contents = datas[0].split(",");
				String result = "";
				for (int i = 0; i < contents.length; i++) {
					if (!"".equals(result)) {
						result += ",";
					}
					result += contents[i];
				}
				user_place.setText(result);
			}
		});
	}

	public boolean onTouch(View v, MotionEvent event) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.baby_birthday:
			((InputMethodManager) getSystemService(INPUT_METHOD_SERVICE))
					.hideSoftInputFromWindow(PerfectUserInfoActivity1.this
							.getCurrentFocus().getWindowToken(),
							InputMethodManager.HIDE_NOT_ALWAYS);
			wheel_time.setVisibility(View.VISIBLE);
			wheel_time.setMyVisible();
			break;
		case R.id.user_place:
			location.setVisibility(View.VISIBLE);
			location.setMyVisible();
			break;

		default:
			break;
		}
		return false;
	}
	
	public void profileUserInfo() {
		Intent intent = new Intent(
				PerfectUserInfoActivity1.this,
				ChoooseCardActivity.class);
		if (come_from.equals("yunqi")) {
			if (isTimeSelect()) {
				Toast.makeText(mContext, "您还没有填写预产期，请填写", 1).show();
				return;
			}
			int days = compairTime(theTime)+1;
			if (days > 280 || isBeforeToday(theTime)) {
				Toast.makeText(mContext, "请输入正确的预产期哦", 0).show();
				return;
			}
			intent.putExtra("birthday", String.valueOf(babybirthday));

		} else if (come_from.equals("baby")) {
			if (isTimeSelect()) {
				Toast.makeText(mContext, "您还没有填写宝宝生日，请填写", 1).show();
				return;
			}
			if (!boy_selected && !girl_selected) {
				Toast.makeText(mContext, "您还没有选择宝宝性别，请点击头像选择", 1).show();
				return;
			}
			if (boy_selected && girl_selected) {
				Toast.makeText(mContext, "宝宝性别只能选择男孩或女孩，请点击头像更改", 1).show();
				return;
			}
			if (boy_selected) {
				gender_index = 1;
			} else if (girl_selected) {
				gender_index = 0;
			} else {
			}
			int years =yearsOfTwo(theTime);
			if (years>6 || years<0) {  //限制0~6岁的孩子出生日期在一定的时间段内（不能超过6年前）
				Toast.makeText(mContext, "请输入正确的出生日期哦", 0).show();
				return;
			}
			intent.putExtra("gender", String.valueOf(gender_index));
			intent.putExtra("birthday", String.valueOf(babybirthday));
		} else {
			if (isTimeSelect()) {
				Toast.makeText(mContext, "您还没有填写您的生日，请填写", 1).show();
				return;
			}
			intent.putExtra("birthday", String.valueOf(babybirthday));
		}

		String placeString = user_place.getText().toString();
		intent.putExtra("COMEFROM1", come_from);
		intent.putExtra(KidAction.PLACE_STRING, placeString);
		PerfectUserInfoActivity1.this.startActivity(intent);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode == 100) {
			String predate = data.getStringExtra("PREDATE");
			baby_birthday.setText(predate);
			String[] time = predate.split(",");
			theTime = time;
			baby_birthday.setTextColor(Color.parseColor("#3e3e3e"));
			baby_birthday
					.setText(time[0] + "年" + time[1] + "月" + time[2] + "日");
			Date now = new Date();
			now.setYear(Integer.parseInt(time[0]) - 1900);
			now.setMonth(Integer.parseInt(time[1]) - 1);
			now.setDate(Integer.parseInt(time[2]));
			babybirthday = now.getTime() / 1000;
			isSetTime = true;
		}
	}
	
	public boolean isTimeSelect(){
		return TextUtils.isEmpty(baby_birthday.getText().toString().trim());
		
	}

}
